package TryCode.TCP;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPServer {
    public static void main(String[] args) {
        try {
            // 创建ServerSocket对象，监听指定的端口号
            ServerSocket serverSocket = new ServerSocket(6000);

            System.out.println("服务器已启动，等待客户端连接...");

            // 等待客户端连接
            Socket clientSocket = serverSocket.accept();

            // 获取输入流和输出流
            BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

            // 读取客户端发送的消息
            String clientMessage = in.readLine();
            System.out.println("接收到客户端消息: " + clientMessage);

            // 发送响应给客户端
            out.println("Hello from server");

            // 关闭连接
            clientSocket.close();
            serverSocket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
